﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Quartz;
using User.Api.HttpClients;

namespace Out.TaskRunner.QuartzJobs
{
    public class GetStopDoctorInfoJob : IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(GetStopDoctorInfoJob));

        /// <summary>
        /// 执行成功
        /// </summary>
        public bool IsExecuteSuccess = true;

        /// <summary>
        /// 重试次数
        /// </summary>
        public int RetryTimes = 0;

        public void Execute(IJobExecutionContext context)
        {
            Logger.InfoFormat("Executing job: {0}", context.JobDetail.Key);

            DoTransferDeptAndDoctorInfo();

            while (true)
            {
                if (RetryTimes > 5)
                {
                    IsExecuteSuccess = true;
                    RetryTimes = 0;
                    break;
                }
                
                if (!IsExecuteSuccess)
                {
                    DoTransferDeptAndDoctorInfo();
                }

                RetryTimes++;
            }
        }

        public void DoTransferDeptAndDoctorInfo()
        {
            Console.WriteLine("[{0}] 获取停诊医生信息", DateTime.Now.ToString("MM-dd HH:mm:ss"));


            var request = new GetHaltInfoRequest();
            request.BeginDate = DateTime.Today.ToString("yyyy-MM-dd");
            request.EndDate = DateTime.Today.AddDays(8).ToString("yyyy-MM-dd");


            GetHaltInfoResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetHaltInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetHaltInfoResponse>().Result;

                if (response.ResultCode == "0")
                {
                    using (var ctx = new GdsfybjyWeiXinEntities())
                    {
                        response.HaltList.ForEach(x =>
                        {
                            if (!ctx.StopDoctorInfoes.Any(k => k.deptId == x.DeptId
                                                              && k.doctorId == x.DoctorId
                                                              && k.regDate == x.HaltDate
                                                              && k.scheduleId == x.TimeSlice))
                            {
                                ctx.StopDoctorInfoes.Add(new StopDoctorInfo
                                {
                                    deptId = x.DeptId,
                                    doctorId = x.DoctorId,
                                    regDate = x.HaltDate,
                                    scheduleId = x.TimeSlice,
                                    //doctorName = x.RegType,
                                    //reason = x.Reason,
                                    //shiftCode = x.ShiftCode,
                                    //beginTime = x.BeginTime,
                                    //endTime = x.EndTime,
                                    //replaceDoctorId = x.ReplaceDoctorId,
                                    //replaceDoctorName = x.ReplaceDoctorName,
                                    //orderId = x.OrderId,
                                    state = "0",
                                    createTime = DateTime.Now
                                });
                                ctx.SaveChanges();
                            }
                        });
                    }

                    IsExecuteSuccess = true;

                }
                else
                {
                    IsExecuteSuccess = false;
                }


                if (IsExecuteSuccess)
                {

                    Console.WriteLine("[{0}] 成功获取停诊医生信息", DateTime.Now.ToString("MM-dd HH:mm:ss"));
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内GetStopDoctorInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
            }

        }

    }
}
